// import Vue from "vue"
// import Vuex from "vuex"
// import state from "./state.js"
// import actions from "./action.js"
// import mutations from "./mutation.js"

// Vue.use(Vuex);

// const store = new Vuex.Store({
// 	state,
// 	mutations,
// 	actions,
// 	modules: {}
// })

// export default store
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

let lifeData = {};

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  lifeData = uni.getStorageSync("lifeData");
} catch (e) { };

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ["vuex_user_id", "vuex_user_info", "vuex_identity", "vuex_openid", "vuex_session_key", "vuex_user_login", "vuex_share_id", "vuex_power_01", "vuex_power_02", "vuex_power_03", "vuex_power_04"];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  // 判断变量名是否在需要存储的数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmp = uni.getStorageSync("lifeData");
    // 第一次打开APP，不存在lifeData变量，故放一个{}空对象
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    // 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
    uni.setStorageSync("lifeData", tmp);
  }
}

const store = new Vuex.Store({
  state: {
    // 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
    // 加上vuex_前缀，是防止变量名冲突，也让人一目了然
    vuex_user_id: lifeData.vuex_user_id ? lifeData.vuex_user_id : 47,
    vuex_identity: lifeData.vuex_identity ? lifeData.vuex_identity : "",
    vuex_share_id: lifeData.vuex_share_id ? lifeData.vuex_share_id : "",
    /* #ifdef MP-WEIXIN */
    vuex_user_id: lifeData.vuex_user_id ? lifeData.vuex_user_id : 0,
    vuex_identity: lifeData.vuex_identity ? lifeData.vuex_identity : "",
    vuex_share_id: lifeData.vuex_share_id ? lifeData.vuex_share_id : "",
    /* #endif */
    vuex_user_info: lifeData.vuex_user_info ? lifeData.vuex_user_info : {},
    vuex_openid: lifeData.vuex_openid ? lifeData.vuex_openid : "",
    vuex_session_key: lifeData.vuex_session_key ? lifeData.vuex_session_key : "",
    vuex_user_login: lifeData.vuex_user_login ? lifeData.vuex_user_login : false,
    vuex_power_01: lifeData.vuex_power_01 ? lifeData.vuex_power_01 : "",
    vuex_power_02: lifeData.vuex_power_02 ? lifeData.vuex_power_02 : "",
    vuex_power_03: lifeData.vuex_power_03 ? lifeData.vuex_power_03 : "",
    vuex_power_04: lifeData.vuex_power_04 ? lifeData.vuex_power_04 : "",
    // 如果vuex_version无需保存到本地永久存储，无需lifeData.vuex_version方式
    // vuex_version: "1.0.1",

    isLogin: false,
    isSDKReady: false, // TIM SDK 是否 ready

    conversationActive: {},	// 聊天进行中的会话
    toUserId: "", // 聊天对象id
    conversationList: [],// 会话列表
    currentMessageList: [], // 消息列表
  },
  getters: {

  },
  mutations: {
    $uStore(state, payload) {
      // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
      let nameArr = payload.name.split(".");
      let saveKey = "";
      let len = nameArr.length;
      if (nameArr.length >= 2) {
        let obj = state[nameArr[0]];
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]];
        }
        obj[nameArr[len - 1]] = payload.value;
        saveKey = nameArr[0];
      } else {
        // 单层级变量，在state就是一个普通变量的情况
        state[payload.name] = payload.value;
        saveKey = payload.name;
      }
      // 保存变量到本地，见顶部函数定义
      saveLifeData(saveKey, state[saveKey])
    },

    //更新登录状态
    toggleIsLogin(state, isLogin) {
      state.isLogin = typeof isLogin === 'undefined' ? !state.isLogin : isLogin
    },
    //更新TIMSDK状态
    toggleIsSDKReady(state, isSDKReady) {
      state.isSDKReady = typeof isSDKReady === 'undefined' ? !state.isSDKReady : isSDKReady
    },
    //退出登录重置状态
    reset(state) {
      state.isLogin = false
      state.isSDKReady = false
    },
    //选择好友聊天--创建会话/拼接会话id
    createConversationActive(state, toUserId) {
      state.conversationActive.conversationID = 'C2C' + toUserId
      state.toUserId = toUserId
      state.currentMessageList = []
    },
    //选择已有会话聊天--更新选中会话详情
    updateConversationActive(state, conversationItem) {
      console.log(conversationItem)
      state.conversationActive = Object.assign({}, conversationItem.conversation);
      state.toUserId = conversationItem.conversation.userProfile.userID
      state.currentMessageList = []
    },
    //更新会话列表
    updateConversationList(state, newConversationList) {
      state.conversationList = newConversationList
    },
    /**
     * 将消息插入当前会话列表
     * 调用时机：收/发消息事件触发时
     * @param {Object} state
     * @param {Message[]|Message} data
     * @returns
     */
    pushCurrentMessageList(state, data) {
      // 还没当前会话，则跳过
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.conversationID === state.conversationActive.conversationID)
        state.currentMessageList = [...state.currentMessageList, ...result]
      } else if (data.conversationID === state.conversationActive.conversationID) {
        state.currentMessageList = [...state.currentMessageList, data]
      }
      console.log(state.currentMessageList)
    },
    /**
     * 滑到顶部请求更多的历史消息
     * */
    unshiftCurrentMessageList(state, data) {
      console.log(data)
      if (data) {
        state.currentMessageList = [...data, ...state.currentMessageList]
      }
    },
  },
  actions: {

  },
  modules: {

  },
})

// 从缓存中取得相同的key进行覆盖操作
// let lifeData = uni.getStorageSync("lifeData") || {};
// for (let key in lifeData) {
//   if (store.state.hasOwnProperty(key)) {
//     store.commit("$uStore", {
//       name: key,
//       value: lifeData[key]
//     })
//   }
// }

export default store;